<?php
namespace app\admin\controller;

class Index extends Base {
	public function index() {
		//判断cookie是否存在，如果存在自动登录
		$admin = \think\Cookie::get('admin');
		if ($admin) {
			session('admin', $admin);
		}
		//判断是否登录
		if (session('?admin')) {
			$this->redirect("Home/index");
		} else {
			session('mess', '您还没有登录');
			$this->redirect("Index/login");
		}
	}

	public function login() {
		if (session('?admin')) {
			$this->redirect("Home/index");
		}
		if (IS_POST) {
			if (I('post.vcode/s') != session('vcode')) {
				return $this->error('验证码错误！');
			}
			session('vcode', null);
			$mUsers = D('api/Users');
			$map = [
				'username' => I('post.username/s'),
				'password' => md5(I('post.password/s')),
			];
			$res = $mUsers->where($map)->find();
			if (!$res) {
				return $this->error('用户或者密码错误！');
			}
			if (I('post.online/s') == 'true') {
				\think\Cookie::set('admin', $res, 3600 * 12 * 14);
			}
			//加入session
			session('admin', $res);
			$this->redirect("Index");
		} else {
			$mess = '';
			if (session('?mess')) {
				$mess = session('mess');
				session('mess', null);
			}
			return $this->fetch('login', [
				'mess' => $mess,
			]);
		}
	}

	public function vcode() {
		$Vcode = new \app\common\Vcode();
		$Vcode->doimg();
		session('vcode', $Vcode->getCode());
	}
}
